//
//  DawnGridAdapter.swift
//  Test
//
//  Created by cuicheng on 2021/8/25.
//

import UIKit

import RxCocoa
class DawnGridAdapter: NSObject {
    var gridV: UICollectionView!
    var grid: [DawnGridModel]? {
        didSet{
            _setup()
        }
    }
    private var cellType = DawnGridCell.self
    {
        didSet{
            gridV.register(cellType.classForCoder(), forCellWithReuseIdentifier: cellId)
        }
    }
    private var cellId = "CellId"
    private var disposeBag: DisposeBag!
    var itemSelected: ((DawnGridModel)->())?
    var cellForRow: ((Int, DawnGridModel, UICollectionViewCell)->())?
    required init(_ gridV: UICollectionView) {
        super.init()
        self.gridV = gridV
        _init()
    }
    
    private func _init() {
        disposeBag = DisposeBag()
        gridV.register(cellType.classForCoder(), forCellWithReuseIdentifier: cellId)
        gridV.rx.itemSelected.subscribe(onNext: { [weak self] e in
            guard let mod = self?.grid?[e.item] else { return }
            self?.itemSelected?(mod)
        }).disposed(by: disposeBag)
    }
    
    private func _setup() {
        defer {
            gridV.reloadData()
        }
        gridV.dataSource = nil
        guard let grid = grid else { return }
        let dataSource = Observable.just(grid)
        dataSource.bind(to:
                            gridV.rx.items(cellIdentifier: cellId, cellType: cellType))
        { [weak self] row, mod, cell in
            if cell.isKind(of: DawnGridCell.classForCoder()) {
                self?.configCell(row: row, mod: mod, cell: cell)
            }
            
            self?.cellForRow?(row, mod, cell)
        }.disposed(by: disposeBag)
    }
    
    private func configCell(row: Int, mod: DawnGridModel, cell: DawnGridCell) {
        cell.mod = mod
    }
}
